package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.My_News_Adapter;
import com.example.xianji.BGARefresh.BGANormalRefreshViewHolder;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.My_DuiJie;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class Main_My_NewsActivity extends Activity implements BGARefreshLayoutDelegate {
    /********************我发布的新闻页面***************************/
    private RelativeLayout my_news_back;
    private BGARefreshLayout news_PullToRefreshLayout_two;
    private ListView news_mylistview;
    //    private SharedPreferences sp;
//    private Editor ed;
    private ArrayList<My_DuiJie> news_list = new ArrayList<My_DuiJie>();
    private int page = 1;
    private My_News_Adapter mMy_News_Adapter;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    news_mylistview.setAdapter(mMy_News_Adapter);
                    news_PullToRefreshLayout_two
                            .endRefreshing();
                    break;
                case 2:
                    mMy_News_Adapter.notifyDataSetChanged();
                    news_PullToRefreshLayout_two
                            .endLoadingMore();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__my__news);
        // XJApplication.getInstance().addActivity(this);
        my_news_back = (RelativeLayout) findViewById(R.id.my_news_back);
        news_PullToRefreshLayout_two = (BGARefreshLayout) findViewById(R.id.news_PullToRefreshLayout_two);
        news_mylistview = (ListView) findViewById(R.id.news_mylistview);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        mMy_News_Adapter = new My_News_Adapter(this, news_list);
        my_news_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Main_My_NewsActivity.this.finish();
            }
        });
        get_news();
        news_PullToRefreshLayout_two.setDelegate(this);
        news_PullToRefreshLayout_two.setRefreshViewHolder(new BGANormalRefreshViewHolder(
                this, true));
    }

    public void get_news() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("page", 1);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.qiye_news, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        news_list.clear();
                        JSONArray array = response.getJSONArray("data");
                        if (array.length() == 0) {
                            news_PullToRefreshLayout_two
                                    .endRefreshing();
                            Toast.makeText(Main_My_NewsActivity.this,
                                    "您还没有发布新闻哦！", Toast.LENGTH_SHORT).show();
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array
                                        .getJSONObject(i);
                                My_DuiJie mMy_DuiJie = new My_DuiJie();

                                mMy_DuiJie.setCat_name(object
                                        .getString("cat_name"));
                                mMy_DuiJie.setTitle(object
                                        .getString("news_title"));
                                mMy_DuiJie.setCreated_at(object
                                        .getString("created_at"));
                                mMy_DuiJie.setId(object.getInt("id"));
                                news_list.add(mMy_DuiJie);
                            }
                        }
                    } else {
                        news_PullToRefreshLayout_two
                                .endRefreshing();
                        Toast.makeText(Main_My_NewsActivity.this,
                                response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                    handler.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void get_news_more() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("page", page);
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.qiye_news, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        if (array.length() == 0) {
                            Toast.makeText(Main_My_NewsActivity.this,
                                    "没有更多数据哦", Toast.LENGTH_SHORT).show();
                            news_PullToRefreshLayout_two
                                    .endLoadingMore();
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array
                                        .getJSONObject(i);
                                My_DuiJie mMy_DuiJie = new My_DuiJie();

                                mMy_DuiJie.setCat_name(object
                                        .getString("cat_name"));
                                mMy_DuiJie.setTitle(object
                                        .getString("news_title"));
                                mMy_DuiJie.setCreated_at(object
                                        .getString("created_at"));

                                mMy_DuiJie.setId(object.getInt("id"));

                                news_list.add(mMy_DuiJie);
                            }
                            handler.sendEmptyMessage(2);
                        }
                    } else {
                        news_PullToRefreshLayout_two
                                .endLoadingMore();
                        Toast.makeText(Main_My_NewsActivity.this,
                                response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }


    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        page = 1;
        get_news();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(
            BGARefreshLayout refreshLayout) {
        page++;
        get_news_more();
        return true;
    }

}
